"use client";
import { Form, Input, Button, message, Card } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { useRouter } from "next/navigation";
import styles from "./login.module.css";
import { authControllerLoginUser } from "@/app/servers/api/auth";

interface LoginForm {
  email: string;
  password: string;
}

export default function LoginPage() {
  const router = useRouter();
  const [form] = Form.useForm();

  const onFinish = async (values: LoginForm) => {
    try {
      const response = await authControllerLoginUser(values);
      if (response.data) {
        message.success("登录成功");
        router.push("/manage/coral-class");
        localStorage.setItem("token", response.data.access_token);
        localStorage.setItem("userInfo", JSON.stringify(response.data));
      } else {
        message.error("登录失败");
      }
    } catch {
      message.error("登录失败，请稍后重试");
    }
  };

  return (
    <div className={styles.container}>
      <Card title="珊瑚保护后台管理系统" className={styles.loginCard}>
        <Form
          form={form}
          name="login"
          onFinish={onFinish}
          autoComplete="off"
          layout="vertical"
        >
          <Form.Item
            name="email"
            rules={[
              { required: true, message: "请输入邮箱" },
              { type: "email", message: "请输入有效的邮箱地址" },
            ]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="请输入邮箱"
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请输入密码"
              size="large"
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block size="large">
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}
